package com.org.shichui;

import com.alibaba.fastjson.JSONObject;
import com.org.shichui.common.MesType;
import com.org.shichui.common.SocketMessage;
import com.org.shichui.util.CommonUtils;
import com.org.shichui.websocket.SocketServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Date;

@SpringBootApplication
@EnableScheduling
@EnableTransactionManagement
public class ShichuiApplication {

	public static void main(String[] args) {
		SpringApplication.run(ShichuiApplication.class, args);
	}

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*");
		corsConfiguration.addAllowedHeader("*");
		corsConfiguration.addAllowedMethod("*");
		return corsConfiguration;
	}

	/**
	 * 跨域过滤器
	 *
	 * @return
	 */
	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig()); // 4
		return new CorsFilter(source);
	}
	@Bean
	public TaskScheduler scheduledExecutorService() {
		ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
		scheduler.setPoolSize(1);
		scheduler.setThreadNamePrefix("scheduled-thread-");
		return scheduler;
	}

	@Scheduled(fixedRate = 5000)
	public void reportCurrentTime() {
		SocketMessage sm =new SocketMessage(MesType.PING, CommonUtils.dateToStr(new Date(),"YYYY:MM:DD-hh:mm:ss"));
		SocketServer.sendAll(JSONObject.toJSONString(sm));
	}
}
